import React from "react";
import {Tabs, Modal} from "antd";
import _uniqBy from "lodash/uniqBy";
import TreeSelect from "./TreeSelect";
// import { equals } from "@cbd/utils";
import styles from "./TransactorSelect.less";

import UsersTags from "../usersTags/UsersTags";

import {openNotificationWithIcon} from "../../utils/comm.js";

const {TabPane} = Tabs;

const isTrue = true;

// @connect(({
//   usertreeSelect,
//   loading,
// }) => ({
//   loading,
//   usertreeSelectStore: usertreeSelect,
// }))
const activeTypeArr = [
  "STA",
  "ORG",
  "ROL",
  "GROUP",
  "POSITION",
  "RELATIONSHIP",
  "FUNCTION",
];

class TransactorSelect extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.treeRef = {};
    // this.activeType = 'STA';
    this.state = {
      allSelectData: "",
      activeType: "STA",
    };
  }

  componentDidMount() {
  }

  componentDidUpdate(preProps) {
    const {visible, selectData} = this.props;
    if (visible !== preProps.visible) {
      if (visible) {
        this.setTreesSelectKeys(selectData);
      } else {
        this.setTreesSelectKeys([]);
      }
    }
  }

  componentWillUnmount() {
    // this.activeType = 'STA';
  }

  getTreeRef = (type, treeThis) => {
    this.treeRef[type] = treeThis;
  };

  onTabChage = activeType => {
    // this.activeType = activeType;
    this.setState({activeType});
  };

  // 选中人员
  onCheckedRows = (newSelectedRowKeys, type) => {
    const {selectData} = this.props;
    const {allSelectData} = this.state;
    const tempSelect = allSelectData || selectData;
    // const otherData =
    //   (Array.isArray(tempSelect) && tempSelect.filter(v => (v.type === "RELATIONSHIP" || v.type === "FUNCTION" || v.type === "ORG"))) ||
    //   [];
    const otherData =
      (Array.isArray(tempSelect) && tempSelect.filter(v => (v.type !== type))) ||
      [];
    this.setState({
      allSelectData: _uniqBy([...otherData, ...newSelectedRowKeys], "code"),
    });
  };

  // 选中项
  onCheckedNodes = (
    ischecked,
    node,
    checkedNodes,
    newSelectNodes = [],
    prevSelectedKeys = [],
  ) => {
    const {selectData = []} = this.props;
    const {allSelectData, activeType} = this.state;
    let selectDatas = allSelectData || selectData;
    if (newSelectNodes) {
      if (ischecked) {
        // 过滤新增的选择的node
        const typeNodes = newSelectNodes.filter(item => {
          if (selectDatas.length === 0) return true;
          return !selectDatas.some(sItem => {
            return sItem.code === item.code && sItem.type === item.type;
          });
        });
        selectDatas = [...selectDatas, ...typeNodes];
        /*
      } else if (newSelectNodes.length === 0) {
        selectDatas = selectDatas.filter(item => item.type !== activeType);
      } else {
        selectDatas = selectDatas.filter(item => {
          const isExit = newSelectNodes.some(sItem => {
            return (sItem.code === item.code && sItem.type === item.type);
          });
          return (activeType !== item.type || isExit);
        });
      }
      */
      } else {
        // 比对 prevSelectedKeys与newNodes，删除被去除的项

        const existedMap = (newSelectNodes || []).reduce((map, {code}) => {
          map[code] = true;
          return map;
        }, {});

        const removedKeyMap = (prevSelectedKeys || []).reduce((map, k) => {
          if (!existedMap[k]) {
            map[k] = true;
          }
          return map;
        }, {});

        selectDatas = selectDatas.filter(item => {
          return activeType !== item.type || !removedKeyMap[item.code];
        });
      }
      this.setState({allSelectData: selectDatas});
      this.setTreesSelectKeys(selectDatas);
    }
  };

  onSelectedDataChange = (newSelectDatas = []) => {
    this.setState({allSelectData: newSelectDatas})
  };

  // 删除项
  handleDelSelect = delItem => {
    const {type, code} = delItem || {};
    // const {deleteData} = this.treeRef.STA;
    const {selectData = []} = this.props;
    const {allSelectData} = this.state;
    let selectDatas = allSelectData || selectData;
    selectDatas = selectDatas.filter(sItem => {
      return !(sItem.type === type && sItem.code === code);
    });
    this.setTreesSelectKeys(selectDatas);
    this.setState({allSelectData: selectDatas});
    // deleteData([code]);

    // const {deleteData: deleteDataRol} = this.treeRef.ROL;
    // const {deleteData: deleteDataGroup} = this.treeRef.GROUP;
    // const {deleteData: deleteDataPosition} = this.treeRef.POSITION;
    // deleteDataRol([code]);
    // deleteDataGroup([code]);
    // deleteDataPosition([code]);

  };

  // 清除
  handleClearSelect = () => {
    // const {deleteData} = this.treeRef.STA;
    // const {deleteData: deleteDataRol} = this.treeRef.ROL;
    // const {deleteData: deleteDataGroup} = this.treeRef.GROUP;
    // const {deleteData: deleteDataPosition} = this.treeRef.POSITION;
    // const { allSelectData = [] } = this.state;
    this.setTreesSelectKeys([]);
    this.setState({allSelectData: []},
      // () => {
      // deleteData([]);
      // deleteDataRol([]);
      // deleteDataGroup([]);
      // deleteDataPosition([]);
      // }
    );
  };

  // 重置树中的反显项
  setTreesSelectKeys = selectDatas => {
    activeTypeArr.forEach(activeType => {
      setTimeout(() => {
        const selectedTypeData = selectDatas.filter(
          sitem => sitem.type === activeType,
        );
        const selectedKeys = selectedTypeData.map(sitem => sitem.code);
        const nowTreeRef = this.treeRef[activeType];
        if (nowTreeRef)
          nowTreeRef.setTreeSelectData(selectedKeys, selectedTypeData);
      }, 300);
    });
  };

  // 确定
  handleUsersSelect = () => {
    const {userSelect, selectData} = this.props;
    const {allSelectData} = this.state;
    const nowSelectData = allSelectData || selectData;
    if (userSelect) userSelect(nowSelectData);
    setTimeout(() => {
      this.setState({allSelectData: "", activeType: "STA"});
    }, 100);
  };

  handleCancel = () => {
    const {onCancel} = this.props;
    if (onCancel) {
      onCancel();
      this.setState({allSelectData: "", activeType: "STA"});
    }
  };

  inputItem = node => {
    this.input = node;
  };

  render() {
    const {
      dispatch,
      visible,
      wrapClassName,
      selectData = [],
      title,
      appId,
    } = this.props;
    const {allSelectData, activeType} = this.state;
    const selectDatas = allSelectData || selectData;

    return (
      <Modal
        title={`选择${title || "办理人"}`}
        centered
        width={668}
        destroyOnClose
        visible={visible}
        onOk={this.handleUsersSelect}
        onCancel={this.handleCancel}
        wrapClassName={`${styles.user_modal} ${wrapClassName}`}
      >
        <div className={styles.transactor_box}>
          <div className={styles.select_box}>
            <span className={styles.label}>
              {`已选择${title ||
              "办理人"}：`}
            </span>
            <div className={styles.user_list}>
              {selectDatas.map(item => (
                <UsersTags
                  key={`${item.type}_${item.code}`}
                  label={item.name}
                  onClick={() => this.handleDelSelect(item)}
                />
              ))}
            </div>
            {selectDatas.length > 0 && (
              <span className={styles.clear} onClick={this.handleClearSelect}>
                清空
              </span>
            )}
          </div>
          <div className={styles.tree_box}>
            <Tabs
              defaultActiveKey={activeType}
              activeKey={activeType}
              animated={false}
              onChange={this.onTabChage}
            >
              <TabPane tab="选择人员" key="STA">
                <TreeSelect
                  getTreeRef={treeThis => this.getTreeRef("STA", treeThis)}
                  directoryTree
                  dispatch={dispatch}
                  type="STA"
                  onCheckedRows={this.onCheckedRows}
                  defaultSelectData={selectDatas}
                />
              </TabPane>
              <TabPane tab="选择组织" key="ORG">
                <TreeSelect
                  getTreeRef={treeThis => this.getTreeRef("ORG", treeThis)}
                  directoryTree
                  dispatch={dispatch}
                  isJustLoadOrg={isTrue}
                  checkStrictly={isTrue}
                  type="ORG"
                  onCheckedNodes={this.onCheckedNodes}
                />
              </TabPane>
              <TabPane tab="选择角色" key="ROL">
                <TreeSelect
                  appId={appId}
                  getTreeRef={treeThis => this.getTreeRef("ROL", treeThis)}
                  dispatch={dispatch}
                  directoryTree
                  type="ROL"
                  // onCheckedNodes={this.onCheckedNodes}
                  onCheckedRows={this.onCheckedRows}
                  defaultSelectData={selectDatas}
                />
              </TabPane>
              <TabPane tab="用户组" key="GROUP">
                <TreeSelect
                  appId={appId}
                  getTreeRef={treeThis => this.getTreeRef("GROUP", treeThis)}
                  dispatch={dispatch}
                  directoryTree
                  type="GROUP"
                  // onCheckedNodes={this.onCheckedNodes}
                  onCheckedRows={this.onCheckedRows}
                  defaultSelectData={selectDatas}
                />
              </TabPane>
              <TabPane tab="岗位" key="POSITION">
                <TreeSelect
                  appId={appId}
                  getTreeRef={treeThis => this.getTreeRef("POSITION", treeThis)}
                  dispatch={dispatch}
                  directoryTree
                  type="POSITION"
                  // onCheckedNodes={this.onCheckedNodes}
                  onCheckedRows={this.onCheckedRows}
                  defaultSelectData={selectDatas}
                />
              </TabPane>
              <TabPane tab="关系" key="RELATIONSHIP">
                <TreeSelect
                  appId={appId}
                  getTreeRef={treeThis =>
                    this.getTreeRef("RELATIONSHIP", treeThis)
                  }
                  dispatch={dispatch}
                  directoryTree
                  type="RELATIONSHIP"
                  onCheckedNodes={this.onCheckedNodes}
                />
              </TabPane>
              <TabPane tab="自定义函数" key="FUNCTION">
                <TreeSelect
                  appId={appId}
                  getTreeRef={treeThis => this.getTreeRef("FUNCTION", treeThis)}
                  dispatch={dispatch}
                  directoryTree
                  type="FUNCTION"
                  onCheckedNodes={this.onCheckedNodes}
                  allSelectData={allSelectData}
                  onSelectedDataChange={this.onSelectedDataChange}
                />
              </TabPane>
            </Tabs>
          </div>
        </div>
      </Modal>
    );
  }
}

export default TransactorSelect;
